from django.shortcuts import render, redirect, HttpResponse
from testview.models import Loguser, Person

# Create your views here.


def login(request):
    if request.method == 'POST':
        account = request.POST.get('account')
        password = request.POST.get('password')
        remember = request.POST.get('remember')

        loguser = Loguser.objects.filter(account=account, password=password).first()
        if loguser:
            rep = redirect('/testview/index/')
            if remember == 'on':
                rep.set_cookie('account', account, max_age=60*60*8)
            return rep
        else:
            errmsg = '用户名或密码错误'
            return render(request, 'testview/login.html', {'errmsg': errmsg})

    account = request.COOKIES.get('account', '')
    return render(request, 'testview/login.html', {'account_two': account})


def index(request):
    personList = Person.objects.all()
    return render(request, 'testview/index.html', {'personList': personList})


def addPerson(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        gender = request.POST.get('gender')
        head_img = request.FILES.get('head_img')
        attachment = request.FILES.get('attachment')

        Person.objects.create(name=name, email=email, gender=gender, head_img=head_img, attachment=attachment)
        return redirect('/testview/index/')

    else:
        return render(request, 'testview/add_person.html')


def delPerson(request, personid):
    Person.objects.filter(id=personid).delete()
    return redirect('/testview/index/')


def editPerson(request, personid):
    if request.method == 'POST':
        id = request.POST.get('id')
        name = request.POST.get('name')
        email = request.POST.get('email')
        gender = request.POST.get('gender')
        head_img = request.FILES.get('head_img')
        attachment = request.FILES.get('attachment')

        person_obj = Person.objects.get(id=id)
        person_obj.name = name
        person_obj.email = email
        person_obj.gender = gender
        if head_img:
            person_obj.head_img = head_img
        if attachment:
            person_obj.attachment = attachment

        person_obj.save()

        return redirect('/testview/index/')

    else:
        obj = Person.objects.get(id=personid)
        return render(request, 'testview/edit_person.html', {'person': obj})